package com.mb.app.appused.tools;

import java.util.ArrayList;
import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

public class FragmentUtil {
	private List<Fragment> fragmentList = new ArrayList<Fragment>();
	FragmentManager fragmentManager;
	FragmentTransaction fragmentTransaction;

	public FragmentUtil(FragmentManager fragmentManager) {
		init(fragmentManager);
	}

	public FragmentUtil(FragmentActivity fragmentActivity) {
		init(fragmentActivity.getSupportFragmentManager());
	}

	void init(FragmentManager fragmentManager) {
		this.fragmentManager = fragmentManager;
	}

	public void addFragment(int id, Fragment fragment) {
		fragmentTransaction = fragmentManager.beginTransaction();
		fragmentTransaction.add(id, fragment);
		fragmentList.add(fragment);
		fragmentTransaction.commit();
		// fragmentMap.put(id+"", fragment);
	}

	public void removeFragment(Fragment fragment) {
		if (!fragmentList.contains(fragment))
			return;
		fragmentTransaction = fragmentManager.beginTransaction();
		fragmentTransaction.remove(fragment);
		fragmentList.remove(fragment);
		fragmentTransaction.commit();
	}

	public void showFragment(Fragment fragment) {
		if (fragment == null)
			return;
		if (!fragmentList.contains(fragment))
			return;
		fragmentTransaction = fragmentManager.beginTransaction();

		for (Fragment temp : fragmentList) {
			fragmentTransaction.hide(temp);
		}

		fragmentTransaction.show(fragment);
		fragmentTransaction.commit();
	}

	public void showFragment(Fragment... fragments) {
		if (fragments == null)
			return;
		fragmentTransaction = fragmentManager.beginTransaction();
		for (Fragment temp : fragmentList) {
			fragmentTransaction.hide(temp);
		}
		
		for (Fragment temp : fragments) {
			if (fragmentList.contains(temp)) {
				fragmentTransaction.show(temp);
			}
		}
		fragmentTransaction.commit();
	}

	public void showFragment(int index) {
		if (fragmentList == null || index < 0 || index > fragmentList.size() - 1)
			return;
		Fragment temp = fragmentList.get(index);
		showFragment(temp);
	}

}
